#coding=utf-8
"""
forms.py

Created by reedhong on 2011-10-18.
Copyright (c) 2011 __MyCompanyName__. All rights reserved.
"""

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

from account.models import UserProfile

    
class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=16)
    first_name = forms.CharField(max_length=4)
    password = forms.CharField(max_length=32)
    warn = ""
        
    def __init__(self, request=None, *args, **kwargs):
        self.user_cache = None
        super(RegistrationForm, self).__init__(*args, **kwargs)
        
    def clean(self):
        username = self.cleaned_data.get("username", None)
        if not username:
            self.warn = u"请填写手机号!"
            raise forms.ValidationError(u"请填写手机号!")
        else:
            try:
                user = User.objects.get(username__iexact=username)
                self.user_cache = user
                self.warn = u'该手机号已经注册，无需重复注册!'
                raise forms.ValidationError(u"该手机号已经注册，无需重复注册!")
            except User.DoesNotExist:
                pass
            
        password = self.cleaned_data.get("password", None)
        if not password:
            self.warn = u"请输入密码!"
            raise forms.ValidationError(u"请输入密码!")
        
        return self.cleaned_data
            
    def clean_password(self):
        password = self.cleaned_data["password"]
        return password.lower()
    
    def save(self):
        """
        Create the new 'User' and 'UserProfile', 'UserStatus',
        and returns the 'User'        
        """
        user = User(username=self.cleaned_data['username'],
                             first_name=self.cleaned_data['first_name'])
        password=self.cleaned_data['password']
        user.set_password(password) #将密码密文存储\
        user.save()
        
        # 系统来了新用户，加入到feed中去
        #import pdb;pdb.set_trace()
        feed = Feed(user=user, object_id=user.id, type=FEED_REG_NEW_USER)
        feed.save()
        return user
        
    
class LoginForm(forms.Form):
    username = forms.CharField(max_length=16)
    password = forms.CharField(max_length=32)
    warn = ""

    def __init__(self, request=None, *args, **kwargs):
        """
        If request is passed in, the form will validate that cookies are
        enabled. Note that the request (a HttpRequest object) must have set a
        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
        running this validation.
        """
        self.user_cache = None
        self.request = request
        super(LoginForm, self).__init__(*args, **kwargs)

    def clean(self):
        username = self.cleaned_data.get('username', None)
        if not username:
            self.warn = (u"手机号不能为空!")
            raise forms.ValidationError(u"手机号不能为空!")
        
        password = self.cleaned_data.get('password', None)
        if not password:
            self.warn = (u"密码不能为空!")
            raise forms.ValidationError(u"密码不能为空!")
        
        try:
            user = User.objects.get(username__iexact=username)
        except User.DoesNotExist:
            self.warn = u'该手机号尚未注册，请检查!'
            raise forms.ValidationError(u"该手机号尚未注册，请检查!")     
        
        if username and password:
            #todo
            self.user_cache = authenticate(username=username, password=password)
            if self.user_cache is None:              
                self.warn = u"密码错误，请检查!"
                raise forms.ValidationError(u"密码错误，请检查!")

        # TODO: determine whether this should move to its own method.
        #if self.request:
        #    if not self.request.session.test_cookie_worked():
        #        raise forms.ValidationError(u"cookie支持失败")
        return self.cleaned_data

    def get_user(self):
        return self.user_cache   
    
    def clean_password(self):
        password = self.cleaned_data["password"]
        return password.lower()
    
class ProfileForm(forms.Form):
    """
    user profile setting form
    """       
    gender =  forms.ChoiceField(choices=UserProfile.GENDER_CHOICES, label=u"性别")
    relationship_status =  forms.ChoiceField(choices=UserProfile.RELATIONSHIP_CHOICES, label=u"情感状态")
    birthday_year = forms.CharField(max_length=4,widget=forms.TextInput(attrs={'size':'4'}))
    birthday_month = forms.CharField(max_length=2,widget=forms.TextInput(attrs={'size':'2'}))
    birthday_day = forms.CharField(max_length=2,widget=forms.TextInput(attrs={'size':'2'}))    
    country = forms.CharField(label=u"国家", required=False)
    location = forms.CharField(label=u"现居地", required=False)
    introduction = forms.CharField(label=u'个人介绍', widget=forms.Textarea,required=False)

    def save(self, user): 
        try:
            profile = user.userprofile
        except UserProfile.DoesNotExist:
            profile = UserProfile(user=user)     
        profile.gender = self.cleaned_data.get('gender')
        profile.relationship_status = self.cleaned_data.get('relationship_status')
        
        birthday_year = self.cleaned_data.get('birthday_year', 0)
        if birthday_year:
            profile.birthday_year = birthday_year
        birthday_month = self.cleaned_data.get('birthday_month', 0)
        if birthday_month:
            profile.birthday_month = birthday_month
        birthday_day = self.cleaned_data.get('birthday_day', 0)
        if birthday_day:
            profile.birthday_day = birthday_day 
                       
        profile.country = self.cleaned_data.get('country')
        profile.location = self.cleaned_data.get('location')
        profile.introduction = self.cleaned_data.get('introduction')
        profile.save()
        return profile      
     
     
class AvatarForm(forms.Form):
    avatar  = forms.FileField(error_messages={'required': 
                                                   u"请选择本地文件上传"})     
                                                     
      